package com.uniknow.app.manager;

import java.util.ArrayList;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;

import com.uniknow.app.AppConfig;
import com.uniknow.app.bin.TBSMS;
import com.uniknow.app.util.StringUtils;

public class SMSManager extends BaseManager<TBSMS>{
	final static Uri SMS_URI_ALL = Uri.parse("content://sms/");
	
	public SMSManager(Context context, Class<TBSMS> clazz) {
		super(context, clazz);
	}
	/**
	 * 获取指定时间后的短信记录
	 * 
	 * @param mContext
	 * @param startDate
	 *            "不包括毫秒级"
	 * @return
	 */
	public ArrayList<TBSMS> GetSMSList(int startDate) {
		String startime = "";// 1970年1月1日0点作为"unix纪元"的原点
		if (startDate == 0) {
			startime = "0";// 查找全部通话记录
		} else {
			startime = startDate + "000";// 补全毫秒级
		}

		ArrayList<TBSMS> SMSList = new ArrayList<TBSMS>();
		ContentResolver cr = mContext.getContentResolver();

		final Cursor cursor = cr.query(SMS_URI_ALL,// uri
				new String[] { "_id", "address", "person", "body", "date","type" },// String[] projection
				"date" + ">?",// String selection
				new String[] { startime },// String[] selectionArgs
				"date asc");// 排序字段
		if (cursor != null) {
			while (cursor.moveToNext()) {
				TBSMS sms = new TBSMS();
				// SMS.setPhoneNumber(cursor.getColumnIndex(""));
				// System.out.println("SMS:"+cursor.getInt(0)+"--"+cursor.getString(1)+"--"+cursor.getString(2)+"--"+cursor.getString(3)+"--"+cursor.getString(4)+"--"+cursor.getInt(5));
				sms.setTel(cursor.getString(1));
				sms.setName(cursor.getString(2));
				sms.setBody(cursor.getString(3));
				sms.setDate(StringUtils.FormatEpoch(cursor.getString(4)));
				sms.setType(cursor.getInt(5));
				sms.setSize(cursor.getString(3).length());
				SMSList.add(sms);
			}
			cursor.close();
		}
		System.out.println("SMSList = " + SMSList.size());
		return SMSList;

	}

	/**
	 * 获取Know数据库中sms表的通话记录最后一次通话记录时间
	 * 
	 * @param db
	 * @return epcho
	 */
	public static int GetSMSLastDate(SQLiteDatabase db) {
		int lastSMSDate = 0;
		String sql = "select date from " + AppConfig.TB_PHONE_SMS
				+ " limit (select count(1) from " + AppConfig.TB_PHONE_SMS
				+ ") offset  (select count(1) from " + AppConfig.TB_PHONE_SMS
				+ " )-1";
		Cursor cursor = db.rawQuery(sql, null);
		if (cursor.moveToNext()) {
			lastSMSDate = cursor.getInt(0);
		}
		return lastSMSDate;
	}

	/**
	 * 插入短信到数据库操作,这里插入操作改为事务操作，对于大量插入操作速度是嗷嗷的！
	 * 
	 * @param SMSList
	 * @param db
	 */	
	public void InsertSMS(ArrayList<TBSMS> SMSList){
		SQLiteDatabase db = dataBaseHelper.getWritableDatabase();
		db.beginTransaction();
		try {
			for (TBSMS sms : SMSList) {
				db.execSQL(
						"INSERT INTO " + AppConfig.TB_PHONE_SMS	+ "(name,type,date,tel,body,size) VALUES(?,?,?,?,?,?)",
						new Object[] {sms.getName(),sms.getType(),sms.getDate(),sms.getTel(),sms.getBody(),sms.getSize()
					});
			}
			db.setTransactionSuccessful();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			db.endTransaction();
		}

	}

}

/**
 * URI主要有：
 * 
 * content://sms/ 所有短信 content://sms/inbox 收件箱 content://sms/sent 已发送
 * content://sms/draft 草稿 content://sms/outbox 发件箱 content://sms/failed 发送失败
 * content://sms/queued 待发送列表
 * 
 * 
 * sms主要结构：
 * 
 * _id => 短消息序号 如100 thread_id => 对话的序号 如100 address =>
 * 发件人地址，手机号.如+8613811810000 person => 发件人，返回一个数字就是联系人列表里的序号，陌生人为null date => 日期
 * long型。如1256539465022 protocol => 协议 0 SMS_RPOTO, 1 MMS_PROTO read => 是否阅读
 * 0未读， 1已读 status => 状态 -1接收，0 complete, 64 pending, 128 failed type => 类型
 * 1是接收到的，2是已发出 ALL = 0;INBOX = 1; SENT = 2;DRAFT = 3;OUTBOX = 4;FAILED =
 * 5;QUEUED = 6; body => 短消息内容 service_center => 短信服务中心号码编号。如+8613800755500
 * 
 * String[] projection = new String[]{"address", "body"}; Cursor cursor =
 * getContentResolver().query(uri, projection, "where .." new String[]{"", ""},
 * "order by ..")
 */
